package com.wuyou.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.wuyou.domain.Result;
import com.wuyou.domain.vo.ApiResult;
import com.wuyou.domain.vo.EsHouseVO;
import com.wuyou.domain.vo.HouseVO;
import com.wuyou.dto.HouseInputInfoDTO;
import com.wuyou.dto.ToEmail;
import com.wuyou.entity.*;
import com.wuyou.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author cxy
 * @since 2022-09-29
 */
@RestController
@RequestMapping("/house")
@Api(value = "房源信息接口")
public class HouseController {

    @Autowired
    private IHouseService houseService;

    @Autowired
    private IHouseDetailsService houseDetailsService;

    @Autowired
    private IProvincesService provincesService;

    @Autowired
    private ICitiesService citiesService;

    @Autowired
    private IAreasService areasService;

    @Autowired
    private IFurnitureService furnitureService;

    @Autowired
    private ITagService tagService;

    //注入MQ对象
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Resource
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private RestTemplate restTemplate;


    @GetMapping("/getAllProvinces")
    @ApiOperation(value = "查询所有省份")
    public Result getAllProvinces() {
        try {
            List<Provinces> provincesList = provincesService.list();
            return Result.OK().setData(provincesList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.ERROR();
        }
    }

    @PostMapping("/getAllCities")
    @ApiOperation(value = "查询当前省下的所有市")
    public Result getAllCities(Integer provinceId) {
        try {
            List<Cities> citiesList = citiesService.list(new QueryWrapper<Cities>().eq("provinceid", provinceId));
            return Result.OK().setData(citiesList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.ERROR();
        }
    }

    @PostMapping("/getAllAreas")
    @ApiOperation(value = "查询当前市下的所有区县")
    public Result getAllAreas(Integer cityId) {
        try {
            List<Areas> areasList = areasService.list(new QueryWrapper<Areas>().eq("cityid", cityId));
            return Result.OK().setData(areasList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.ERROR();
        }
    }

    @GetMapping("/getAllFurnitures")
    @ApiOperation(value = "查询所有设施")
    public Result getAllFurnitures() {
        List<Furniture> furnitureList = furnitureService.list();
        return Result.OK().setData(furnitureList);
    }

    @GetMapping("getAllTags")
    @ApiOperation(value = "查询所有标签")
    public Result getAllTags() {
        List<Tag> tagList = tagService.list();
        return Result.OK().setData(tagList);
    }

    /**
     * 房源信息录入
     *
     * @param houseInputInfoDTO
     * @return
     */
    @PostMapping
    public Result inputHouseInfo(HouseInputInfoDTO houseInputInfoDTO) {
        try {
            //判断用户是否登录
            // Host host = (Host) SecurityUtils.getSubject().getPrincipal();
//            if (host == null){
//                return Result.R(ResultEnum.TOKEN_INVALID);
//            }
            //根据前台传的参数信息 增加
            houseService.insertHouseInfo(houseInputInfoDTO);
            return Result.OK();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.ERROR();
        }
    }

    /**
     * 模糊搜索 (租金,户型,城市id)  分页
     *
     * @param houseVO  房源Vo对象
     * @param pageNum  当前页数
     * @param pageSize 每页展示条数
     * @return
     */
    @PostMapping("/findHouseInfoList")
    @ApiOperation(value = "多条件查询房源信息（后台展示）")
    public Result findHouseInfoList(@RequestBody(required = false) HouseVO houseVO,@RequestParam(defaultValue = "1") Integer pageNum,
                                    @RequestParam(defaultValue = "5")Integer pageSize) {
        try {
            //房源列表查询展示(三级联动, 所属城市,所属商圈,所属小区  及模糊搜索功能, 分页展示)
            PageInfo<HouseVO> houses = houseService.findHouseInfoList(houseVO,pageNum, pageSize);
            return Result.OK().setData(houses);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.ERROR();
        }
    }


    @PostMapping("/getHouseInfoById/{id}")
    public Result getHouseInfoById(@PathVariable("id") Long[] id) {
        try {
            House house = houseService.getById(id);
            HouseDetails houseDetails = houseDetailsService.getOne(new QueryWrapper<HouseDetails>().eq("house_id", id));
            List list = new ArrayList();
            list.add(house);
            list.add(houseDetails);
            return Result.OK().setData(list);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.ERROR();
        }
    }


    //审核商品 auditGoods
    @PostMapping("/auditHouse")
    public Result auditGoods(Long[] HouseIds, Integer auditStatus) {
        try {
            //判断登录态


            if (HouseIds.length == 0 || auditStatus == null) {
                return Result.ERROR();
            }
            //修改房源审核状态
            houseService.auditHouse(HouseIds, auditStatus);
            //判断前台传过来的 状态 是否为 1 (审核通过)
            if (auditStatus == 1) {
                // 审核通过 发送消息
                rocketMQTemplate.convertAndSend("auditHouse", Arrays.toString(HouseIds));
            } else if (auditStatus == 2) {
                //不通过 发邮件
                ToEmail toEmail = new ToEmail();
                toEmail.setTos(from);
                toEmail.setSubject("房源审核结果通知");
                toEmail.setContent("[无忧家] 尊敬的房主,您好,很抱歉,您上传的房源信息未通过审核,具体原因为:.....");
                sendEmail(toEmail);
            }
            return Result.OK();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.ERROR();
        }

    }

    public void sendEmail(ToEmail toEmail) {
        //创建简单邮件消息
        SimpleMailMessage message = new SimpleMailMessage();
        //谁发的
        message.setFrom(from);
        //谁要接收
        message.setTo(toEmail.getTos());
        //邮件标题
        message.setSubject(toEmail.getSubject());
        //邮件内容
        message.setText(toEmail.getContent());
        javaMailSender.send(message);
    }
    //区域找房
    @GetMapping("findNearbyHouse")
    public Result findNearbyHouse(@RequestParam(defaultValue = "1") Integer pageNum,
                                  @RequestParam(defaultValue = "5")Integer pageSize) {

        try {
            Result result = restTemplate.getForEntity("https://www.mxnzp.com/api/ip/self?app_id=qhtllynonlrhrtqd&app_secret=cFptdDFQS1kwcUNWaE80cDVoQ0FQZz09", Result.class).getBody();
            String ip = (String)JSON.parseObject(JSON.toJSONString(result.getData()), Map.class).get("ip");

            String url = "https://eolink.o.apispace.com/ipguishu/ip/geo/v1/district?ip=" + ip;
            //请求头
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.set("X-APISpace-Token", "9bekgn3vipfd2pbfhxxgrsaq7gelz23v");
            requestHeaders.set("Authorization-Type", "apikey");
            //封装请求头
            HttpEntity<MultiValueMap<String, Object>> formEntity = new HttpEntity<MultiValueMap<String, Object>>(requestHeaders);
            ApiResult body = restTemplate.exchange(url, HttpMethod.GET, formEntity, ApiResult.class).getBody();

            Map map = JSON.parseObject(JSON.toJSONString(body.getData()), Map.class);
            PageInfo<HouseVO> houses = houseService.findHouseInfoList(new HouseVO().setArea(map.get("district").toString()),pageNum, pageSize);
            if (houses.getList().size() <= 0) {

                houses = houseService.findHouseInfoList(new HouseVO().setCity(map.get("city").toString()),pageNum, pageSize);
            }
            return Result.OK().setData(houses);
        } catch (RestClientException e) {
            e.printStackTrace();
            return Result.ERROR();
        }
    }

    //搜索展示房源信息(ES复合查询)
    @RequestMapping("multiConditionFindHouse")
    public Result muchConditionFindHouse(@RequestBody(required = false) EsHouseVO esHouseVO, @RequestParam(defaultValue = "1") Integer pageNum,
                                         @RequestParam(defaultValue = "5")Integer pageSize) throws Exception {

        try {
            return Result.OK().setData(houseService.multiConditionFindHouse(esHouseVO,pageNum,pageSize));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.ERROR();
        }
    }
}

